﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Controls;

namespace SHomeWorkshop.LunarSF.StudentInfosManager.ValidationRules
{
    /// <summary>
    /// 班级名称数值验证类。
    /// </summary>
    public class ClassRule : LValidationRule
    {
        public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
        {
            string text = Format(value.ToString());
            if (string.IsNullOrWhiteSpace(text))
                return new ValidationResult(false, "“××班级”必须填写在[1,99]之间的数值。"); //验证失败

            if (AllIsNumberChars(text))
            {
                int _value;
                if (int.TryParse(text, out _value))
                {
                    if (_value >= 1 && _value <= 99)
                        return new ValidationResult(true, null); //验证OK
                    else
                        return new ValidationResult(false, "“××班级”必须填写在[1,99]之间的数值。"); //验证失败
                }
                else
                    return new ValidationResult(false, "“××班级”必须填写在[1,99]之间的数值。"); //验证失败
            }
            else
                return new ValidationResult(false, "“××班级”必须填写在[1,99]之间的数值。"); //验证失败
        }

        public static string Format(string origin)
        {
            if (string.IsNullOrWhiteSpace(origin)) return "";
            return origin.Replace(" ", "").Replace("　", "").Replace("\t", "").Replace(",", "").Replace("，", "");
        }

        /// <summary>
        /// 判断是否全是汉字。★空字符串返回“false”。
        /// </summary>
        /// <param name="text">源文本。</param>
        /// <returns>如果都在[０，９]或[0,9]范围内，返回真。</returns>
        public static bool AllIsNumberChars(string text)
        {
            if (string.IsNullOrWhiteSpace(text)) return false;

            for (int i = 0; i < text.Length; i++)
            {
                if (text[i] >= '0' && text[i] <= '9') continue;
                else if (text[i] >= '０' && text[i] <= '９') continue;
                else return false;
            }

            return true;
        }
    }
}
